<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css"  media="all">
  <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
  <link rel="stylesheet" href="__CSS__/admin.css"  media="all">
  <!--<script src="{$Think.config.httpFlag}{$Think.config.google_map_url}" async="async"></script>-->
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
  <style>
    .layui-upload-img{
      width: 100px;
    }
    .uploadimgbox{
        position: relative;
        display: inline-block;

        width: 100px;
        height: 100px;
        margin-right: 15px;
    }

    .uploadimgbox  .layui-icon{
        position: absolute;
        right: -15px;
        top: -15px;
        cursor: pointer;
    }
  </style>
</head>
<body>
<div style="margin-top: 20px;">
</div>

<form class="layui-form" id="admin" >
  <input type="hidden" name="type" value="CITY">
  <div class="layui-form-item">
    <label class="layui-form-label">所属国家</label>
    <div class="layui-input-inline">
      <input name="groupid" value="{if !empty($groupid)}{$groupid}{/if}" type="hidden">
      <input name="countryname" value="{if !empty($country)}{$country}{/if}" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" readonly type="text">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">排序权重</label>
    <div class="layui-input-inline">
      <input name="sort_weight" id="sort_weight" style="width:100px;" value="{notempty name="$menu"}{$menu['sort_weight']}{/notempty}" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" type="number">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">中文名</label>
    <div class="layui-input-inline" style="position: relative">
      <input name="name" id="chname" value="{notempty name="$menu"}{$menu['name']}{/notempty}" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" type="text">
      <div id="addressbox"></div>
    </div>
  </div>


  <div id="map" style="margin-left: 110px;width: 600px;margin-bottom: 30px">
    <img src="{notempty name='$menu.pic1'}{$menu['pic1']}{/notempty}" width="600" alt="">
  </div>

  <div class="layui-form-item">
    <label class="layui-form-label">英文名</label>
    <div class="layui-input-inline">
      <input name="eng_name" id="enname" value="{notempty name='$menu'}{$menu['eng_name']}{/notempty}" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" type="text">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">Viator关联destid</label>
    <div class="layui-input-inline">
      <input name="destid" id="destid" value="{notempty name='$menu'}{$menu['destid']}{/notempty}" placeholder="请输入" autocomplete="off" class="layui-input" type="text">
    </div>
    <div class="layui-inline" style="line-height: 38px;">
      {if empty($menu['getgoods'])}<span style="color:red">未开启</span>{else}<span style="color:green">已开启</span>{/if}
    </div>
    {notempty name="$menu.id"}{notempty name="$menu.getgoods"}
    <div class="layui-inline">
      <a data-id="{$menu.id}" class="layui-btn layui-bn-sm layui-btn-normal pullViatorDataByDestId">拉取 Viator 商品</a>
    </div>
    {/notempty}{/notempty}


  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">订单系统ID</label>
    <div class="layui-input-inline">
      <input name="kbx_id" id="kbx_id" value="{notempty name='$menu'}{$menu['kbx_id']}{/notempty}" placeholder="请输入" autocomplete="off" class="layui-input" type="text">
    </div>
  </div>

  <!--<div class="layui-form-item">-->
    <!--<label class="layui-form-label">城市分类</label>-->
    <!--<div class="layui-input-inline" style="width: 400px">-->
      <!--<select id="categorytags" lay-filter="addCategoryTags" lay-search>-->
        <!--<option value="">请选择城市分类</option>-->
        <!--{volist name="categorytags" id="vo"}-->
        <!--<option value="{$vo.tag_id}">{$vo.tag_name}</option>-->
        <!--{/volist}-->
      <!--</select>-->
    <!--</div>-->
    <!--<span id="addCategoryTags" data-name="" data-id="" class="layui-btn layui-btn-danger layui-btn-sm" style="margin-top:4px">添加</span>-->
  <!--</div>-->
  <!--<div class="layui-form-item">-->
    <!--<label class="layui-form-label">已选分类</label>-->
    <!--<div class="layui-input-inline" style="width: 500px;min-height:40px;background: #eee" id="categorytagnames">-->
      <!--{notempty name="$cateArr"}-->
      <!--{volist name="cateArr" id="vo"}-->
      <!--<span class="layui-btn layui-btn-sm layui-btn-normal delcategorytag" data-id="{$vo['tag_id']}" style="margin: 5px 10px">{$vo['tag_name']}<i class="layui-icon"></i></span>-->
      <!--{/volist}-->
      <!--{/notempty}-->
    <!--</div>-->
  <!--</div>-->
  <!--<input name="categorytagids" id="categorytagids" value='{notempty name="$categorytagsStr"}{$categorytagsStr}{/notempty}' type="hidden">-->
  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">备注</label>
    <div class="layui-input-block" style="max-width:500px;">
      <textarea placeholder="请输入内容"  class="layui-textarea" name="description">{notempty name="$menu"}{$menu['description']}{/notempty}</textarea>
    </div>
  </div>

  <input name="gid" id="gid" value="{notempty name='$menu'}{$menu['gid']}{/notempty}"type="hidden">
  <input name="lat" id="lat" value="{notempty name='$menu'}{$menu['lat']}{/notempty}"type="hidden">
  <input name="lng" id="lng" value="{notempty name='$menu'}{$menu['lng']}{/notempty}" type="hidden">
  <input name="pic1" id="pic1" value="{notempty name='$menu'}{$menu['pic1']}{/notempty}" type="hidden">
  <input name="address" id="address" value="{notempty name='$menu'}{$menu['address']}{/notempty}" type="hidden">

  {notempty name="$menu"}
  <input type="hidden" name="id" value="{$menu.id}">
  {/notempty}

  <div class="layui-form-item">
    <label class="layui-form-label">商城首图</label>
    <div class="layui-upload" style="margin:0 110px ">
      <button type="button" class="layui-btn" id="test2">图片上传（格式：jpg,png,gif,jpeg）</button>
      <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        预览图：
        <div class="layui-upload-list" id="demo2">
            {volist name="$thumb" id="vo"}
            {if !empty($vo)}
            <span class="uploadimgbox"><img class="layui-upload-img" src="{$vo}"><i class="layui-icon">&#x1006;</i></span>
            {/if}
            {/volist}
        </div>
      </blockquote>
    </div>
      <input id="upload-thumb" type="hidden" name="thumb" value="{notempty name='$menu'}{$menu['thumb']}{/notempty}">
  </div>

  <div class="layui-form-item">
    <label class="layui-form-label">小程序首图</label>
    <div class="layui-upload" style="margin:0 110px ">
      <button type="button" class="layui-btn" id="test3">图片上传（格式：jpg,png,gif,jpeg）</button>
      <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        预览图：
        <div class="layui-upload-list" id="demo3">
          {volist name="$wxx_thumb" id="vo"}
          {if !empty($vo)}
          <span class="uploadimgbox"><img class="layui-upload-img" src="{$vo}"><i class="layui-icon">&#x1006;</i></span>
          {/if}
          {/volist}
        </div>
      </blockquote>
    </div>
    <input id="upload-thumb3" type="hidden" name="wxx_thumb" value="{notempty name='$menu'}{$menu['wxx_thumb']}{/notempty}">
  </div>

  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="admin">立即提交</button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>

</form>


<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>

<script>
    layui.use(['upload','form'], function(){
        var form = layui.form;
        var upload = layui.upload;
        var upload1 = layui.upload;
        //执行实例
        //多图片上传
        upload.render({
            elem: '#test2'
            ,url: "{:url('common/upload')}"
            ,multiple: true
            ,done: function(res){
                //上传完毕回调
                layer.closeAll('loading');
                if(res.code == 2) {
                    $('#demo2').append('<span class="uploadimgbox"><img class="layui-upload-img" src="'+res.src+'"><i class="layui-icon">&#x1006;</i></span>');
                    $('#upload-thumb').val($('#upload-thumb').val()+","+res.src);
                } else {
                    layer.msg(res.msg);
                }
            }
            ,error: function(){
                layer.closeAll('loading');
                layer.msg("上传失败");
                return false;
            }
            ,before:function(){
                layer.load(2);
            }
        });

        upload1.render({
            elem: '#test3'
            ,url: "{:url('common/upload')}"
            ,multiple: true
            ,done: function(res){
                //上传完毕回调
                layer.closeAll('loading')
                if(res.code == 2) {
                    $('#demo3').append('<span class="uploadimgbox"><img class="layui-upload-img" src="'+res.src+'"><i class="layui-icon">&#x1006;</i></span>');
                    $('#upload-thumb3').val($('#upload-thumb3').val()+","+res.src);
                } else {
                    layer.msg(res.msg);
                }
            }
            ,error: function(){
                layer.closeAll('loading')
                layer.msg("上传失败");
                return false;
            }
            ,before:function(){
                layer.load(2);
            }

        });

        //首页分类标签选择
        form.on('select(addCategoryTags)', function(data){
            var tripid=data.value;
            if(tripid!==''){
                $("#addCategoryTags").attr("data-id",tripid);
            }
        });

        $("#addCategoryTags").on("click",function () {
            var tagid = $("#categorytags").val();
            var tagname = $("#categorytags").next().find('input').val();
            var tagname_text = $("#categorytags option:selected").text();
            if(tagname!=tagname_text){
                if(tagname!="" && tagname!='请选择标签'){
                    //地区标签分类
                    var tag_type = 5;
                    $.post("/admin/taglable/ajaxAddTag",{tag_name:tagname,tag_type:tag_type},function(data){
                        layer.msg(data.msg);
                        if(data.code==1){
                            $("#categorytags option:not(:first-child)").remove();
                            var str = "";
                            var curTagId = data.data.curTagId;
                            $.each(data.data.list,function(i,v){
                                str += "<option value='"+v.id+"'>"+v.name+"</option>";
                            })
                            $("#categorytags").append(str);
                            addCategoryTags(curTagId,tagname);
                            form.render('select');
                        }
                    },'json')
                }else{
                    layer.msg("请选择标签");
                }
                return false;
            }
            addCategoryTags(tagid,tagname);
        });
        //添加分类的方法
        function addCategoryTags(tagid,tagname){
            var tagids=$("#categorytagids").val();
            if(tagids!='' ){
                var ids=tagids.split(",");
                if($.inArray(tagid,ids)==-1){
                    //存在分类且不包含该分类
                    ids.push(tagid);
                    tagids = ids.join(",");
                }else{
                    layer.msg("请勿重复添加标签");
                    return false;
                }
            }else{
                tagids = tagid;
            }
            var tagspan='<span class="layui-btn layui-btn-sm layui-btn-normal delcategorytag" data-id="'+tagid+'" style="margin: 5px 10px">'+tagname+'<i class="layui-icon"></i></span>';
            $("#categorytagnames").append(tagspan);
            $("#categorytagids").val(tagids);
        }
        $(document).on("click",'.delcategorytag',function () {
            var dataid=$(this).attr("data-id");
            var tagids=$("#categorytagids").val();
            var ids=tagids.split(",");
            var newid="";
            for(var i=0 ; i < ids.length; i++){
                if(ids[i]&&dataid!=ids[i]){
                    if(!newid){
                        newid+=ids[i];
                    }else{
                        newid+=","+ids[i];
                    }
                }
            }
            $("#categorytagids").val(newid);
            $(this).remove();
        });
        //拉取城市下的vaitor数据
        $('.pullViatorDataByDestId').click(function () {
            var city_id = $(this).attr('data-id');
            layer.confirm('是否确认更新该城市下的viator商品数据？确认后，脚本可能需要等待一段时间才能运行结束，请耐心等待！',function () {
                if(city_id==undefined || city_id==''){
                    layer.msg('缺少城市ID,请刷新后重试！');return false;
                }
                var loading = layer.load(2);
                var url = "/api/Viator/getViatorGoodsByCity?city_id=" + city_id;
                $.post("{:url('admin/goods/checkViatorGoodsByCityCache')}",{},function (res) {
                    if(res.code > 0){
                        $.get(url);
                        setTimeout(function () {
                            layer.closeAll();
                            layer.alert('后台数据拉取中！<br>请稍等十分钟左右后进行查看！<br>如果仍无法查到数据，请联系技术部进行日志跟踪！');
                            $('.pullViatorDataByDestId').addClass('layui-btn-disabled').css("pointer-events","none");
                            return false;
                        },1000)
                    }else{
                        layer.closeAll();
                        layer.msg(res.msg);
                        return false;
                    }
                });
            })
        })
    });

    $("#demo2").on("click",".layui-icon",function(){
        $(this).parent().remove();
        thumb("demo2");
    });

    $("#demo3").on("click",".layui-icon",function(){
        $(this).parent().remove();
        thumb1("demo3");
    });


    function thumb(obj){
        var thumbs="";
        $("#"+obj).find("img").each(function(){
            var url=$(this).attr("src");
            thumbs+=","+url;
        });
        $("#upload-thumb").val(thumbs);
    }

    function thumb1(obj){
        var thumbs="";
        $("#"+obj).find("img").each(function(){
            var url=$(this).attr("src");
            thumbs+=","+url;
        });
        $("#upload-thumb3").val(thumbs);
    }


</script>
<script>
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form;
        $(window).on('load', function() {
            form.on('submit(admin)', function(data) {
                $.ajax({
                    url:"{:url('admin/City/addcity')}",
                    data:$('#admin').serialize(),
                    type:'post',
                    async: false,
                    success:function(res) {
                        layer.msg(res.msg);
                        if(res.code == 1) {
                            setTimeout(function(){
                                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                parent.layer.close(index); //再执行关闭
                            },1500)
                        }
                    }
                })
                return false;
            });

              //地图优化成谷歌地图API接口
              //延迟加载输入
              var timeoutId = 0;
              //英文输入绑定事件
              $("#chname").on("input",function(){
                  hiddenAddressBox();
                  clearTimeout(timeoutId);
                  var value = $(this).val();
                  timeoutId = setTimeout(function(){
                      getAddressList(value);
                  },500)
              });
              //点击地址设置地址
              $("#addressbox").on("click","span",function(){
                  var address = $(this).html();
                  setAddress(address);
              });
              //取消地址列表框
              $("body").on("click",function(){
                  hiddenAddressBox()
              })
              //清掉地址列表
              function hiddenAddressBox()
              {
                  $("#addressbox").html("");
              }
              //选中地点
            var googleMapData = [];
            //如果详细地址未匹配到信息则使用列表中的数据
            function setAddressByList(res,googleMapData,address)
            {
                if(res.data.candidates.length < 1 || "OK" != res.data.status){
                    if(googleMapData.length > 0){
                        $.each(googleMapData,function (i,v) {
                            if(v.formatted_address==address){
                                $.ajaxSettings.async = false;
                                $.post('{:url("/api/common/getGoogleImgByLatLng")}',{
                                    lat:v.geometry.location.lat,
                                    lng:v.geometry.location.lng,
                                    zoom:8
                                },function (img_res) {
                                    if(img_res.code>0){
                                        res.data.google_map_img = img_res.data.google_map_img;
                                        res.data.status = 'OK';
                                    }
                                },'json')
                                $.ajaxSettings.async = true;
                                res.data.candidates.push(v);return false;
                            }
                        })
                    }
                }

                return res;
            }
              function setAddress(address) {
                  //切换成接口访问
                  $.post('{:url("/api/common/getGoogleAddressList")}',{address:address,getMap:true,zoom:10},function (res) {
                      if(res.code>0){
                          var res = setAddressByList(res,googleMapData,address);
                          var candidates = res.data.candidates;
                          if(candidates.length>0 && "OK" == res.data.status){
                              $("input[name=lat]").val(candidates[0].geometry.location.lat);
                              $("input[name=lng]").val(candidates[0].geometry.location.lng);
                              $("input[name=gid]").val(candidates[0].place_id);
                              $("input[name=eng_name]").val(candidates[0].name);
                              $("input[name=address]").val(address);
                              $("input[name=pic1]").val(res.data.google_map_img);
                              $("#map img").attr('src',res.data.google_map_img);
                          }
                      }
                  },'json')
              }
              //获取地址列表
              function getAddressList(address) {
                  var addressbox="";
                  if(address=='' || address==undefined){
                      return false;
                  }
                  //切换成接口访问
                  $.post('{:url("/api/common/getGoogleAddressList")}',{address:address},function (res) {
                      if(res.code>0){
                          var candidates = res.data.candidates;
                          googleMapData = res.data.candidates;
                          if(candidates.length > 0 && "OK" == res.data.status){
                              $.each(candidates,function (i,v) {
                                  if(i>4){
                                      return false;
                                  }
                                  addressbox+="<span>"+v.formatted_address+"</span>";
                              })
                              console.log(addressbox);
                              $("#addressbox").html(addressbox);
                          }
                      }
                  },'json')
              }
        });
    });
</script>
</body>
</html>
